package org.yang.common.utils.map;

import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * map工具类
 *
 * @author: lslands
 * @description:
 * @version：v1.0
 * @date: 2024/5/26 15:49
 */
@Configuration
public class MapUtil {


    /**
     * 获取Map对象指定key的value
     *
     * @param map 目标对象
     * @param key 指定key
     * @return Object
     */
    public static Object getValueByKey(Map<String, Object> map, String key) {
        //判断是否包含指定的键名
        Map<String, Object> objectMap = isKey(map, key);
        for (Map.Entry<String, Object> entry : objectMap.entrySet()) {
            Object value = entry.getValue();
            if (value instanceof Map) {
                Object result = getValueByKey((Map<String, Object>) value, key);
                if (result != null) {
                    return result;
                }
            }
        }
        return null;
    }

    /**
     * 获取未知层级map对象(包括集合)，指定key的value
     *
     * @param map 目标对象
     * @param key 指定key
     * @return Object
     */
    public static Object getValue(Map<String, Object> map, String key) {
        Map<String, Object> objectMap = isKey(map, key);
        for (Object value : objectMap.values()) {
            if (value instanceof Map) {
                Object result = getValue((Map<String, Object>) value, key);
                if (result != null) {
                    return result;
                }
            } else if (value instanceof List) {
                for (Object item : (List) value) {
                    if (item instanceof Map) {
                        Object result = getValue((Map<String, Object>) item, key);
                        if (result != null) {
                            return result;
                        }
                    }
                }
            } else if (value instanceof Set) {
                for (Object item : (Set) value) {
                    if (item instanceof Map) {
                        Object result = getValue((Map<String, Object>) item, key);
                        if (result != null) {
                            return result;
                        }
                    }
                }
            }
        }
        return null;
    }

    /**
     * 判断是否包含指定键名
     *
     * @param map map对象
     * @param key 指定键名
     * @return Map<String, Object> map
     */
    public static Map<String, Object> isKey(Map<String, Object> map, String key) {
        return map.containsKey(key) ? map : null;
    }
}
